import { login } from '@/api/login'
import { logout } from '@/api/indivdual/logout'
import router from '@/router'
import { setTokenTime, getToken, setToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import store from '@/store'
export default {
  namespaced: true,
  state: () => ({
    token: getToken(),
    siderType: true,
    lang: localStorage.getItem('lang') || 'zh',
    user: JSON.parse(localStorage.getItem('user')) || '',
    cmsPermissionRole: JSON.parse(localStorage.getItem('roleItem')) || '',
    buttonRole: JSON.parse(localStorage.getItem('buttonRole')) || ''
  }),
  mutations: {
    updateUser(state, newUser) {
      state.user = newUser
    },
    updateRole(state, newRole) {
      state.cmsPermissionRole = newRole
    },
    updateButtonRole(state, newButtonRole) {
      state.buttonRole = newButtonRole
    }

  },
  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            if (res.message === '失败') {
              ElMessage.error(res.data.fail)
            } else {
              ElMessage.success(res.message)
              setToken(res.data.csrfToken)
              setTokenTime()
              localStorage.setItem('user', JSON.stringify(res.data.user))
              localStorage.setItem('roleItem', JSON.stringify(res.data.cmsPermissionRole))
              localStorage.setItem('buttonRole', JSON.stringify(res.data.button))
              commit('updateUser', res.data.user)
              commit('updateRole', res.data.cmsPermissionRole)
              commit('updateButtonRole', res.data.button)
              setTimeout(() => {
                router.replace('/')
              }, 500)
            }
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 退出
    logout() {
      removeToken()
      router.replace('/login')
      return new Promise((resolve, reject) => {
        const userId = store.state.app.user.id
        logout(userId)
          .then((res) => {
            ElMessage.success(res.message)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
}
